package top.houry.limit;

import java.security.SecureRandom;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.IntStream;

public class CountRateLimiter {
    private AtomicLong counter = new AtomicLong(0);
    private static long timestamp = System.currentTimeMillis();
    private long limit;

    public CountRateLimiter(long limit) {
        this.limit = limit;
    }

    public boolean tryAcquire() {
        long now = System.currentTimeMillis();
        if (now - timestamp < 1000) {
            if (counter.get() < limit) {
                counter.incrementAndGet();
                return true;
            } else {
                return false;
            }
        } else {
            counter = new AtomicLong(0);
            timestamp = now;
            return false;
        }
    }

    public static void main(String[] args) {
        CountRateLimiter rateLimiter = new CountRateLimiter(100);
        IntStream.range(0,2000).forEach(v ->{
            boolean result = rateLimiter.tryAcquire();
            System.out.println("请求 " + v + ": " + (result ? "通过" : "拒绝"));
            try {
                // 模拟请求间隔 (可以先注释掉，然后再试放开，观察2次效果)
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

    }

}
